<?php
/*
 * @author: Thanhpv
 * @date: 8/9/2014
 * 
 */

class Frame extends CI_Controller{
	
	public function __construct(){
		parent::__construct();
		$this->load->library('session');
		$this->load->helper("url");
	}
	
	public function index(){
		$this->load->Model("mimage");
		session_start();
		$userId = "";
		$imageName = "";
		if(isset($_SESSION["userId"])){
			$userId = $_SESSION["userId"];
		}else 
			redirect($this->config->item("RedirectURL"));
		
		if(isset($_SESSION["imageName"])){
			$imageName = $_SESSION["imageName"];
			$dotPos = strpos ( $imageName, "." );
			$extension = substr ( $imageName, $dotPos, strlen ( $imageName ) );
			if (strcmp ( $extension, ".png" ) == 0) {
				$this->session->set_flashdata ( "Error", "Please use jpeg or jpg extension photo" );
				redirect ( base_url ( "index.php/ImageUpload/ImageUpload/index" ) );
				return;
			}
		}else{
			$_SESSION["imageName"] = "default.jpg";
			$imageName = $_SESSION["imageName"];
			//copy default image to userId folder
			$folderName = $userId;
			$destination = './UserUploads/' . $folderName;
			$mode = 0777;
			$mkdirError = ! is_dir ( $destination ) ? mkdir ( $destination, $mode ) : true;
			if (! $mkdirError) {
				$this->session->set_flashdata ( "Error", "There is an error with server" );
				redirect ( base_url ( "index.php/ImageUpload/ImageUpload/index" ) );
				return;
			}
			
			$copyFile = copy("./UserUploads/default.jpg", $destination."/default.jpg");
			if(!$copyFile){
				$this->session->set_flashdata ( "Error", "There is an error with server" );
				redirect ( base_url ( "index.php/ImageUpload/ImageUpload/index" ) );
				return;
			}
		}
		if(isset($_SESSION["imagePath"]))
			$size = $this->mimage->getSize($_SESSION["imagePath"]);
		else
			$size = $this->mimage->getSize("./UserUploads/$userId/default.jpg");
		$data['userId'] = $userId;
		$data ['imageName'] = (! isset ( $_SESSION ["isFramed"] )) ? ((isset($_SESSION["imagePath"]))?$_SESSION ["imagePath"]:(base_url()."./UserUploads/$userId/default.jpg")) : $_SESSION ["framePath"];
		$data['funcType'] = 2;
		$data ["width"] = $size [0];
		$data ["height"] = $size [1];
		$this->load->view('FunctionFrame/index', $data);
	}
	
	public function process(){
		if(isset($_POST)){
			$frameNumber = !(isset($_POST['line-style']))?1:$_POST['line-style'];
			$this->load->Model('mimage');
			
			$framePath = "/images/Frames/$frameNumber.png";
			$this->mimage->imageFrame($framePath, $frameNumber);
			redirect(base_url("index.php/FunctionFrame/Frame/index"));
		}
	}
}